package resolver

/*
Copyright 2021-2025 The k8gb Contributors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Generated by GoLic, for more details see: https://github.com/AbsaOSS/golic
*/

import (
	"context"
	"fmt"
	"reflect"
	"regexp"

	k8gbv1beta1 "github.com/k8gb-io/k8gb/api/v1beta1"
	"sigs.k8s.io/controller-runtime/pkg/client"
)

const (
	// GeoIP strategy
	GeoStrategy = "geoip"
	// RoundRobin strategy
	RoundRobinStrategy = "roundRobin"
	// Failover strategy
	FailoverStrategy = "failover"
	// DefaultTTLSeconds
	DefaultTTLSeconds = 30
)

var geoTagRegex = regexp.MustCompile(`^[a-zA-Z\-\d]+$`)

// ResolveGslbSpec fills Gslb by spec values. It executes always, when gslb is initialised.
// If spec value is not defined, it will use the default value. Function returns error if input is invalid.
func (r *Resolver) ResolveGslbSpec(ctx context.Context, gslb *k8gbv1beta1.Gslb, client client.Client) error {
	if client == nil {
		return fmt.Errorf("nil client")
	}
	if !reflect.DeepEqual(gslb.Spec, r.spec) {
		// set predefined values if missing in the yaml
		if gslb.Spec.Strategy.DNSTtlSeconds == 0 {
			gslb.Spec.Strategy.DNSTtlSeconds = DefaultTTLSeconds
		}
		// Validate Gslb.Spec.Strategy
		r.errorSpec = r.specValidator.Struct(gslb.Spec.Strategy)
		if r.errorSpec == nil {
			r.errorSpec = client.Update(ctx, gslb)
		}
		r.spec = gslb.Spec
	}
	return r.errorSpec
}
